using UnityEngine;
using System.Collections;

public class Fov : MonoBehaviour {

 public float maxDistance, angle;
 public Color view, notView;
 
 Transform player, mTransform;
 
 // Use this for initialization
 void Start () 
{
	  this.mTransform = this.transform;
	  this.renderer.material.color = this.notView;
	  GameObject o = GameObject.FindGameObjectWithTag("Player");
	  if (o == null)
	  {
		   this.enabled = false;
		   Debug.Log ("Pas de Player sur la scene");
		   return;
  	  }
}
 
 // Update is called once per frame
 void LateUpdate () 
 {
	  if (this.ViewPlayer())
	  this.renderer.material.color = this.view;
	  else
	  this.renderer.material.color = this.notView;
 }
 
 bool ViewPlayer()
{
	  float playerDistance = Vector3.Distance (this.player.position, this.mTransform.position);
	  if (playerDistance > this.maxDistance)
	  {
		   Debug.Log ("Distance");
		   return false;
	  }
	  Vector3 playerDirection = this.player.position - this.mTransform.position;
	  if (Vector3.Angle(this.mTransform.forward, playerDirection) > this.angle / 2F)
	  {
		   Debug.Log("Angle : " + Vector3.Angle (this.mTransform.forward, playerDirection));
		   return false;
	  }
	  Ray ray = new Ray(this.mTransform.position, playerDirection);
	  Debug.DrawLine (ray.origin, ray.origin + playerDirection);
	  RaycastHit info;
	  
	  if(!Physics.Raycast(ray, out info, playerDistance))
	  {
		   Debug.Log("see");
		   return true;
	  }
	  else
	  {
	   	    Debug.Log("Collide : " + info.transform.name);
	  }
	  return false;
}
}